package com.example.wifi4server;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.Socket;

public class CloseSocketTask implements Runnable {

    private WeakReference<ListenerTask> mRefListenerTask;
    public boolean mbReopen;

    public CloseSocketTask(ListenerTask listenerTask,boolean bReOpen){
        mbReopen = bReOpen;
        mRefListenerTask = new WeakReference<ListenerTask>(listenerTask);
    }
    @Override
    public void run() {
        if (mRefListenerTask.get().serverSocket != null) {
            try {
                mRefListenerTask.get().serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mRefListenerTask.get().serverSocket = null;
        }
        for (int index = 0; index < mRefListenerTask.get().mListConnectSocket.size(); index++) {
            Socket curSocket = mRefListenerTask.get().mListConnectSocket.get(index);
            ReadTask readTask = mRefListenerTask.get().mListReadTask.get(index);
            readTask.bStop = true;
            mRefListenerTask.get().mListReadTask.remove(index);
            for (int curIndex = 0; curIndex < mRefListenerTask.get().mListWriteTask.size(); curIndex++) {
                WriteTask writeTask = mRefListenerTask.get().mListWriteTask.get(curIndex);
                if (writeTask.mSocket == curSocket) {
                    writeTask.bStop = true;
                    mRefListenerTask.get().mListWriteTask.remove(curIndex);
                }
            }

            try {
                curSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mRefListenerTask.get().mListConnectSocket.remove(index);
        }
        if (mbReopen == true)
          mRefListenerTask.get().mHandler.sendEmptyMessage(MainActivity.REOPEN_SSID);
    }
}
